package example.linklist_array;

// https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/   删除链表的倒数第 N 个结点
public class Demo1 {
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode fast = head;
        int i = 0;
        while (i < n) {
            fast = fast.next;
            i++;
        }
        ListNode slow = head;
        ListNode prev = null;
        while (fast != null) {
            fast = fast.next;
            prev = slow;
            slow = slow.next;
        }
        if (prev != null) {
            prev.next = slow.next;
        } else {
            //如果是prev是null移除的就是head
            return head.next;
        }
        return head;
    }

    public static void main(String[] args) {
        System.out.println();
    }


    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}
